<template>
  <div class="app-containers">
    <div class="box-padding-16">
      <div class="box-padding-16-flex">
        <div class="box-padding-16-flex-left">
          <div class="line"></div>
          <div class="box-title">数据总览</div>
          <div class="box-subtitle">{{ getCurrentDateTime() }} 更新</div>
        </div>
        <div class="times">
          <el-date-picker v-model="paramsQuery.year" type="year" placeholder="选择日期" format="yyyy"
            value-format="yyyy"></el-date-picker>
        </div>
      </div>
      <div class="card-container" style="margin-top: 16px">
        <div class="cards-wrapper">
          <div v-for="(item, index) in items" :key="index" class="card-item"
            :class="{ 'last-card': index === items.length - 1 }">
            <div class="card-content" :style="{ background: item.color }">
              <div class="title">{{ item.title }}</div>
              <div class="value">{{ item.value }} {{ item.unit }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 生产数据 -->
    <div class="section">
      <el-row>
        <el-col :span="18">
          <div class="box-padding-16 box-margin-left-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">生产数据</div>
              </div>
            </div>
            <div class="chart-row">
              <div ref="productionBarChart" class="bar-chart"></div>
              <!--              <div ref="productionPieChart" class="pie-chart"></div>-->
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="box-padding-16 box-margin-right-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">生产数据</div>
              </div>
            </div>
            <div class="chart-row">
              <!--              <div ref="productionBarChart" class="bar-chart"></div>-->
              <div ref="productionPieChart" class="pie-chart"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 销售数据 -->
    <div class="section">
      <el-row>
        <el-col :span="18">
          <div class="box-padding-16 box-margin-left-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">销售数据</div>
              </div>
            </div>
            <div class="chart-row">
              <div ref="salesBarChart" class="bar-chart"></div>
              <!--              <div ref="salesPieChart" class="pie-chart"></div>-->
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="box-padding-16 box-margin-right-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">销售数据</div>
              </div>
            </div>
            <div class="chart-row">
              <!--              <div ref="salesBarChart" class="bar-chart"></div>-->
              <div ref="salesPieChart" class="pie-chart"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 主要设备运行数据 -->
    <div class="section">
      <el-row>
        <el-col :span="18">
          <div class="box-padding-16 box-margin-left-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">主要设备运行数据</div>
              </div>
            </div>
            <div class="chart-row">
              <div ref="equipmentBarChart" class="bar-chart"></div>
              <!--              <div ref="equipmentPieChart" class="pie-chart"></div>-->
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="box-padding-16 box-margin-right-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">主要设备运行数据</div>
              </div>
            </div>
            <div class="chart-row">
              <!--              <div ref="equipmentBarChart" class="bar-chart"></div>-->
              <div ref="equipmentPieChart" class="pie-chart"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 用电数据 -->
    <div class="section">
      <el-row>
        <el-col :span="18">
          <div class="box-padding-16 box-margin-left-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">用电数据</div>
              </div>
            </div>
            <div class="chart-row">
              <div ref="electricityLineChart" class="bar-chart"></div>
              <!--              <div ref="electricityPieChart" class="pie-chart"></div>-->
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="box-padding-16 box-margin-right-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">用电数据</div>
              </div>
            </div>
            <div class="chart-row">
              <!--              <div ref="electricityLineChart" class="bar-chart"></div>-->
              <div ref="electricityPieChart" class="pie-chart"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 安全环保数据 -->
    <div class="section">
      <el-row class="safe-wrap">
        <el-col :span="12">
          <el-row>
            <el-col :span="24">
              <div class="box-padding-16 box-margin-left-none">
                <div class="box-padding-16-flex">
                  <div class="box-padding-16-flex-left">
                    <div class="line"></div>
                    <div class="box-title">安全环保数据</div>
                  </div>
                </div>
                <!-- 第一行：巡检折线图 + 两个饼图 -->
                <div class="chart-row">
                  <div ref="inspectionLineChart" class="half-chart"></div>
                  <!--                  <div class="pie-row">-->
                  <!--                    <div ref="regionPieChart" class="pie-charts"></div>-->
                  <!--                    <div ref="levelPieChart" class="pie-charts"></div>-->
                  <!--                  </div>-->
                </div>
                <!-- 第二行：隐患柱状图 + 两个饼图 -->
                <!--                <div class="chart-row">-->
                <!--                  <div ref="hazardBarChart" class="half-chart"></div>-->
                <!--                  <div class="pie-row">-->
                <!--                    <div ref="typePieChart" class="pie-charts"></div>-->
                <!--                    <div ref="threeViolationsPieChart" class="pie-charts"></div>-->
                <!--                  </div>-->
                <!--                </div>-->
              </div>
            </el-col>
            <el-col :span="24" style="margin-top: 16px">
              <div class="box-padding-16 box-margin-left-none">
                <div class="box-padding-16-flex">
                  <div class="box-padding-16-flex-left">
                    <div class="line"></div>
                    <div class="box-title">安全环保数据</div>
                  </div>
                </div>
                <!-- 第一行：巡检折线图 + 两个饼图 -->
                <!--                <div class="chart-row">-->
                <!--                  <div ref="inspectionLineChart" class="half-chart"></div>-->
                <!--                  <div class="pie-row">-->
                <!--                    <div ref="regionPieChart" class="pie-charts"></div>-->
                <!--                    <div ref="levelPieChart" class="pie-charts"></div>-->
                <!--                  </div>-->
                <!--                </div>-->
                <!-- 第二行：隐患柱状图 + 两个饼图 -->
                <div class="chart-row">
                  <div ref="hazardBarChart" class="half-chart"></div>
                  <!--                  <div class="pie-row">-->
                  <!--                    <div ref="typePieChart" class="pie-charts"></div>-->
                  <!--                    <div ref="threeViolationsPieChart" class="pie-charts"></div>-->
                  <!--                  </div>-->
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="12">
          <el-row>
            <el-col :span="24">
              <div class="box-padding-16 box-margin-right-none box-right">
                <div class="box-padding-16-flex">
                  <div class="box-padding-16-flex-left">
                    <div class="line"></div>
                    <div class="box-title">安全环保数据</div>
                  </div>
                </div>

                <!-- 第二行：隐患柱状图 + 两个饼图 -->
                <div class="chart-row" style="margin-top: 16px">
                  <!--              <div ref="hazardBarChart" class="half-chart"></div>-->
                  <div class="pie-row">
                    <div ref="regionPieChart" class="pie-charts"></div>
                    <div ref="levelPieChart" class="pie-charts"></div>
                    <!--                <div ref="typePieChart" class="pie-charts"></div>-->
                    <!--                <div ref="threeViolationsPieChart" class="pie-charts"></div>-->
                  </div>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="box-padding-16 box-margin-right-none box-right" style="padding: 0 0">
                <!--                <div class="box-padding-16-flex">-->
                <!--                  <div class="box-padding-16-flex-left">-->
                <!--                    <div class="line"></div>-->
                <!--                    <div class="box-title">安全环保数据</div>-->
                <!--                  </div>-->
                <!--                </div>-->
                <!-- 第一行：巡检折线图 + 两个饼图 -->
                <!--            <div class="chart-row">-->
                <!--              <div ref="inspectionLineChart" class="half-chart"></div>-->
                <!--              <div class="pie-row">-->
                <!--                <div ref="regionPieChart" class="pie-charts"></div>-->
                <!--                <div ref="levelPieChart" class="pie-charts"></div>-->
                <!--              </div>-->
                <!--            </div>-->
                <!-- 第二行：隐患柱状图 + 两个饼图 -->
                <div class="chart-row" style="margin-top: 16px">
                  <!--              <div ref="hazardBarChart" class="half-chart"></div>-->
                  <!--                  <div class="pie-row">-->
                  <!--                    <div ref="regionPieChart" class="pie-charts"></div>-->
                  <!--                    <div ref="levelPieChart" class="pie-charts"></div>-->
                  <!--                                    <div ref="typePieChart" class="pie-charts"></div>-->
                  <!--                                    <div ref="threeViolationsPieChart" class="pie-charts"></div>-->
                  <!--                  </div>-->
                  <div class="pie-row" style="margin-top: 6px">
                    <!--                <div ref="regionPieChart" class="pie-charts"></div>-->
                    <!--                <div ref="levelPieChart" class="pie-charts"></div>-->
                    <div ref="typePieChart" class="pie-charts"></div>
                    <div ref="threeViolationsPieChart" class="pie-charts"></div>
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </div>
    <!-- 备品备件数据 -->
    <div class="section">
      <el-row>
        <el-col :span="12">
          <div class="box-padding-16 box-margin-left-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">备品备件数据</div>
              </div>
            </div>
            <div class="chart-row">
              <div ref="sparePartsComboChart" class="spare-parts-chart"></div>
              <!--              <div ref="usageComboChart" class="spare-parts-chart"></div>-->
            </div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="box-padding-16 box-margin-right-none">
            <div class="box-padding-16-flex">
              <div class="box-padding-16-flex-left">
                <div class="line"></div>
                <div class="box-title">备品备件数据</div>
              </div>
            </div>
            <div class="chart-row">
              <!--              <div ref="sparePartsComboChart" class="spare-parts-chart"></div>-->
              <div ref="usageComboChart" class="spare-parts-chart"></div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import {
  totalProduction,
  totalSales,
  productionDays,
  totalPower,
  hiddenDanger,
  productionline,
  productionpie,
  salesline,
  salespie,
  equipmentline,
  equipmentpie,
  electricline,
  electricpie,
  inspectionline,
  workshoppie,
  levelpie,
  hazardline,
  hazardtypepie,
  violationpie,
  spareline,
  usageline,
} from "@/api/home.js";

export default {
  data() {
    return {
      gradientColors: [
        // 原有配色
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FAB2FF" },
            { offset: 1, color: "#5644FF" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#7AECF8" },
            { offset: 1, color: "#48DE94" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FEA492" },
            { offset: 1, color: "#FF4C52" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#A5A1FF" },
            { offset: 1, color: "#1F90FF" },
          ],
        },
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(81, 85, 198, 1)" },
            { offset: 1, color: "rgba(81, 85, 198, .6)" },
          ],
        },

        // 新增12条匹配配色
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FF4D9E" },
            { offset: 1, color: "#9B5DE5" },
          ],
        }, // 胭脂粉紫
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#00F5FF" },
            { offset: 1, color: "#00A896" },
          ],
        }, // 霓虹青绿
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FFE066" },
            { offset: 1, color: "#F48C06" },
          ],
        }, // 日落黄橙
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#4CC9F0" },
            { offset: 1, color: "#3A0CA3" },
          ],
        }, // 冰蓝科技
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#52B788" },
            { offset: 1, color: "#2D6A4F" },
          ],
        }, // 森林绿
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FF6B6B" },
            { offset: 1, color: "#C1121F" },
          ],
        }, // 珊瑚红
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(72, 191, 227, 1)" },
            { offset: 1, color: "rgba(30, 58, 138, 0.7)" },
          ],
        }, // 天蓝透明
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#F15BB5" },
            { offset: 1, color: "#7209B7" },
          ],
        }, // 紫罗兰
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#90E0EF" },
            { offset: 1, color: "#0077B6" },
          ],
        }, // 薄荷蓝
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FFF3B0" },
            { offset: 1, color: "#F77F00" },
          ],
        }, // 柠檬黄橙
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "rgba(86, 68, 255, 0.9)" },
            { offset: 1, color: "rgba(25, 25, 112, 0.5)" },
          ],
        }, // 深紫透明
        {
          type: "linear",
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [
            { offset: 0, color: "#FF006E" },
            { offset: 1, color: "#9D0208" },
          ],
        }, // 玫瑰深红
      ],
      items: [
        {
          title: "本年累计生产",
          value: "0",
          color: "linear-gradient(351.54deg, #4468FD -7.1%, #49ADFF 93.49%)",
          unit: " 万吨",
        },
        {
          title: "本年累计销售",
          value: "0",
          color: "linear-gradient(349.2deg, #02ADED 6.47%, #21DCFA 91.94%)",
          unit: " 万吨",
        },
        {
          title: "本年生产天数",
          value: "0",
          color: "linear-gradient(351.54deg, #0AD0A1 -7.1%, #69D488 93.49%)",
          unit: " 天",
        },
        {
          title: "本年累计用电",
          value: "0",
          color: "linear-gradient(351.54deg, #9666F7 -7.1%, #B38FFA 93.49%)",
          unit: " MWH",
        },
        { title: "本年隐患整改数", value: "0", color: "#9eca7f", unit: "" },
      ],
      value1: "",
      // 生产数据
      productionData: {
        months: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        equipment: ["破碎机", "制砂机", "筛分机"],
        equipmentData: [
          [5, 6, 7, 8, 6, 7, 8, 5, 7, 8, 9, 6], // 破碎机
          [4, 5, 6, 7, 5, 6, 7, 4, 6, 7, 8, 5], // 制砂机
          [3, 4, 5, 6, 4, 5, 6, 3, 5, 6, 7, 4], // 筛分机
        ],
        productionPie: [
          { value: 46, name: "细碎车间" },
          { value: 54, name: "制砂车间" },
          { value: 80, name: "回笼车间" },
          { value: 120, name: "粗碎车间" },
        ],
      },

      // 销售数据
      salesData: {
        months: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        products: ["全部产品", "5-10", "10-20", "20-30", "机制砂"],
        productData: [
          [10, 10, 8, 7, 8, 5, 7, 5, 7, 8, 8, 9], // 全部产品
          [7, 10, 7, 7, 7, 5, 6, 4, 6, 7, 7, 7], // 5-10
          [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3], // 10-20
          [9, 9, 9, 8, 9, 8, 9, 8, 8, 8, 6, 7], // 20-30
          [10, 5, 9, 7, 8, 8, 9, 7, 7, 7, 7, 6], // 机制砂
        ],
        salesPie: [
          { value: 46, name: "5-10" },
          { value: 54, name: "10-20" },
          { value: 80, name: "20-30" },
          { value: 120, name: "机制砂" },
        ],
      },

      // 主要设备运行数据
      equipmentData: {
        months: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        equipment: ["破碎机", "制砂机", "筛分机"],
        equipmentData: [
          [5, 6, 7, 8, 6, 7, 8, 5, 7, 8, 9, 6], // 破碎机
          [4, 5, 6, 7, 5, 6, 7, 4, 6, 7, 8, 5], // 制砂机
          [3, 4, 5, 6, 4, 5, 6, 3, 5, 6, 7, 4], // 筛分机
        ],
        equipmentPie: [
          { value: 46, name: "破碎机车间" },
          { value: 54, name: "制砂机车间" },
          { value: 80, name: "筛分机车间" },
          { value: 120, name: "其他车间" },
        ],
      },

      // 用电数据
      electricityData: {
        months: [
          "1月",
          "2月",
          "3月",
          "4月",
          "5月",
          "6月",
          "7月",
          "8月",
          "9月",
          "10月",
          "11月",
          "12月",
        ],
        lineData: [10, 9, 7, 6, 8, 7, 8, 5, 8, 9, 9, 9],
        pieData: [
          { value: 46, name: "细碎车间" },
          { value: 54, name: "制砂车间" },
          { value: 80, name: "回笼车间" },
          { value: 120, name: "粗碎车间" },
        ],
      },

      // 安全环保数据
      safetyData: {
        // 巡检数据
        inspection: {
          months: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          plan: [20, 22, 25, 28, 30, 32, 35, 30, 28, 25, 22, 20],
          actual: [18, 20, 24, 26, 28, 30, 33, 28, 26, 24, 20, 18],
        },
        threeViolations: [
          { value: 15, name: "违章指挥" },
          { value: 10, name: "违章作业" },
          { value: 8, name: "违反劳动纪律" },
          { value: 5, name: "其他" },
        ],
        // 隐患数据
        hazard: {
          months: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          found: [5, 7, 8, 6, 9, 7, 8, 6, 7, 8, 9, 7],
          fixed: [4, 6, 7, 5, 8, 6, 7, 5, 6, 7, 8, 6],
        },

        // 饼图数据
        pieData: {
          region: [
            { value: 23, name: "破碎车间" },
            { value: 18, name: "回笼车间" },
            { value: 12, name: "采区" },
            { value: 5, name: "道路" },
            { value: 3, name: "办公区" },
          ],
          level: [
            { value: 23, name: "轻微隐患" },
            { value: 18, name: "一般隐患" },
            { value: 5, name: "较大隐患" },
            { value: 3, name: "严重隐患" },
          ],
          type: [
            { value: 23, name: "设备隐患" },
            { value: 12, name: "其他隐患" },
            { value: 5, name: "爆破隐患" },
            { value: 3, name: "边坡隐患" },
          ],
        },
      },

      // 备品备件数据
      sparePartsData: {
        // 备件数量数据
        quantity: {
          months: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          spareParts: [
            { name: "托辊", data: [8, 9, 7, 8, 6, 9, 8, 7, 9, 8, 7, 8] },
            { name: "0-5筛网", data: [3, 4, 2, 3, 4, 5, 4, 3, 4, 3, 2, 3] },
            { name: "5-10筛网", data: [2, 3, 1, 2, 3, 4, 3, 2, 3, 2, 1, 2] },
          ],
        },

        // 领用数据
        usage: {
          months: [
            "1月",
            "2月",
            "3月",
            "4月",
            "5月",
            "6月",
            "7月",
            "8月",
            "9月",
            "10月",
            "11月",
            "12月",
          ],
          totalQuantity: [45, 32, 40, 35, 42, 38, 45, 40, 48, 42, 46, 50], // 领用总数量
          totalAmount: [
            8.5, 6.2, 7.8, 6.5, 8.0, 7.2, 8.5, 7.8, 9.0, 8.2, 8.8, 9.2,
          ], // 领用总金额(万元)
        },
      },

      // 图表实例管理
      chartInstances: {},
      paramsQuery: {
        year: new Date().getFullYear().toString(), // '2025'
      },
    };
  },
  created() { },
  watch: {
    "paramsQuery.year": {
      handler() {
        this.loadAllData();
        this.$nextTick(() => {
          this.initAllCharts();
        });
      },
      immediate: false,
    },
  },
  mounted() {
    this.loadAllData();
    this.initAllCharts();

    // ✅ 初始同步一次
    this.$nextTick(() => {
      this.handleResize();
    });

    // ✅ 监听窗口变化
    window.addEventListener("resize", this.handleResize);

    // ✅ 清理监听
    this.$once("hook:beforeDestroy", () => {
      window.removeEventListener("resize", this.handleResize);
      this.disposeAllCharts();
    });
  },
  beforeDestroy() {
    this.disposeAllCharts();
  },
  methods: {
    handleResize() {
      // 1. 让所有图表实例 resize
      Object.values(this.chartInstances).forEach((chart) => {
        chart?.resize();
      });
    },
    getCurrentDateTime() {
      const now = new Date();

      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份从0开始，所以要+1
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");

      return `${year}/${month}/${day} ${hours}:${minutes}`;
    },
    loadAllData() {
      totalProduction(this.paramsQuery).then((res) => {
        this.items[0].value = res.msg;
      });
      totalSales(this.paramsQuery).then((res) => {
        this.items[1].value = res.msg;
      });
      productionDays(this.paramsQuery).then((res) => {
        this.items[2].value = res.msg;
      });
      totalPower(this.paramsQuery).then((res) => {
        this.items[3].value = res.msg;
      });
      hiddenDanger(this.paramsQuery).then((res) => {
        this.items[4].value = res.msg;
      });
    },
    // 统一初始化所有图表
    async initAllCharts() {
      try {
        await Promise.all([
          this.initProductionCharts(),
          this.initSalesCharts(),
          this.initEquipmentCharts(),
          this.initElectricityCharts(),
          this.initSafetyCharts(),
          this.initSparePartsCharts(),
        ]);
      } catch (error) {
        console.error("图表初始化失败:", error);
      }
    },
    // 销毁所有图表实例
    disposeAllCharts() {
      Object.values(this.chartInstances).forEach((chart) => {
        if (chart) chart.dispose();
      });
    },

    // 通用图表初始化方法
    initChart(ref, option) {
      if (!this.chartInstances[ref]) {
        this.chartInstances[ref] = echarts.init(this.$refs[ref]);
      }
      this.chartInstances[ref].setOption(option);
    },

    // 优化后的生产数据图表
    async initProductionCharts() {
      try {
        const [lineData, pieData] = await Promise.all([
          productionline(this.paramsQuery),
          productionpie(this.paramsQuery),
        ]);
        // console.log(lineData)
        const processed = this.processChartData(lineData.data);
        console.log(processed, 'this.processedprocessedprocessed ')
        this.productionData = {
          ...this.productionData,
          ...processed,
          productionPie: pieData.data,
        };
        console.log(this.productionData, 'this.productionData ')
        this.initChart("productionBarChart", this.getProductionBarOption());
        this.initChart("productionPieChart", this.getProductionPieOption());
      } catch (error) {
        console.error("生产数据加载失败:", error);
      }
    },

   

    processChartData(rawData) {
      // 保持月份的原始顺序（按后端返回的先后顺序）
      const months = [];
      const monthSet = new Set();

      // 保持设备的原始顺序（按首次出现的先后顺序）
      const equipment = [];
      const equipSet = new Set();

      rawData.forEach(({ month, equipmentList }) => {
        // 处理月份：只添加未出现过的月份，保持顺序
        if (!monthSet.has(month)) {
          monthSet.add(month);
          months.push(month); // 保持后端返回的月份顺序
        }

        // 处理设备：按首次出现顺序添加到数组
        equipmentList.forEach(({ name }) => {
          if (!equipSet.has(name)) {
            equipSet.add(name);
            equipment.push(name); // 保持后端返回的设备顺序
          }
        });
      });

      // 月份显示格式转换（保留原始顺序）
      const displayMonths = months.map(m => m.slice(-2) + "月");

      // 初始化数据矩阵（按 equipment 的原始顺序）
      const equipmentData = equipment.map(() => Array(months.length).fill(null));

      // 填充数据
      rawData.forEach(({ month, equipmentList }) => {
        const mIndex = months.indexOf(month); // 找到月份在原始顺序中的索引
        if (mIndex !== -1) {
          equipmentList.forEach(({ name, value }) => {
            const eIndex = equipment.indexOf(name); // 找到设备在原始顺序中的索引
            if (eIndex !== -1) {
              equipmentData[eIndex][mIndex] = value;
            }
          });
        }
      });

      return {
        months: displayMonths,
        equipment,
        equipmentData
      };
    },

    getProductionBarOption(processedData) {
      console.log(this.productionData.equipment, 'this.productionData.equipment')
      const equipmentCount = this.productionData.equipment.length;
      const monthCount = this.productionData.months.length;
      const isCrowded = equipmentCount > 6;
      // 核心：动态计算柱子宽度，但默认按4个设备计算宽度
      const defaultDisplayCount = 4;
      let barWidth;
      if (defaultDisplayCount <= 4) {
        barWidth = 30; // 宽松：30px
      } else if (defaultDisplayCount <= 8) {
        barWidth = 20; // 适中：20px
      } else {
        barWidth = 12; // 拥挤：12px
      }
      barWidth = 12;
      // 动态计算barCategoryGap
      const barCategoryGap = equipmentCount > 8 ? "60%" : "80%";
      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          formatter: function (params) {
            return params
              .map((p) => `${p.marker} ${p.seriesName}: ${p.value}万吨`)
              .join("<br/>");
          },
        },
        legend: {
          data: this.productionData.equipment,
          top: "5%",
          icon: "circle",
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 12,
          textStyle: { fontSize: 12 },
          type: equipmentCount > 8 ? "scroll" : "plain",
          pageIconSize: 12,
          pageButtonItemGap: 5,
          // 关键：设置默认选中的图例（前4个设备）
          selected: this.productionData.equipment.reduce((acc, name, index) => {
            acc[name] = index < 4; // 只选中前4个
            return acc;
          }, {}),
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%", // 减小底部空间
          containLabel: true,
          top: equipmentCount > 8 ? "20%" : "15%",
        },
        // 关键改动：彻底移除 dataZoom，无滚动条
        // 不再包含任何 dataZoom 配置项

        xAxis: {
          type: "category",
          data: this.productionData.months, // 完整显示12个月
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: "value",
          name: "万吨",
          nameTextStyle: { padding: [0, 0, 0, -40] },
        },
        // 关键：渲染所有设备系列，但由 legend.selected 控制显示
        series: this.productionData.equipment.map((name, index) => ({
          name,
          type: "bar",
          data: this.productionData.equipmentData[index], // 12个月完整数据
          barWidth: barWidth,
          barCategoryGap: barCategoryGap,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: this.gradientColors[index % 17].colorStops[0].color,
              },
              {
                offset: 1,
                color: this.gradientColors[index % 17].colorStops[1].color,
              },
            ]),
            borderRadius: [3, 3, 0, 0],
          },
          emphasis: {
            focus: "series",
            blurScope: "coordinateSystem",
          },
        })),
      };
    },
    getProductionPieOption() {
      return {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}万吨",
        },
        legend: {
          data: this.productionData.productionPie.map((item) => item.name),
          orient: "horizontal",
          bottom: "0%",
          icon: "circle", // ← 关键：圆点
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12, // 图例间隔（可选）
        },
        series: [
          {
            name: "车间分布",
            type: "pie",
            // animationType: 'scale',
            // animationEasing: 'elasticOut',
            // animationDelay: function (idx) {
            //   return Math.random() * 200;
            // },
            radius: "50%",
            // center: ['50%', '50%'],
            // roseType: 'radius',
            data: this.productionData.productionPie,
            label: {
              formatter: "{b}\n{c}万吨",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.3)",
              },
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
              color: (params) => {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[0]
                        .color,
                  },
                  {
                    offset: 1,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[1]
                        .color,
                  },
                ]);
              },
            },
          },
        ],
      };
    },

    // 销售数据图表
    async initSalesCharts() {
      try {
        const [lineData, pieData] = await Promise.all([
          salesline(this.paramsQuery),
          salespie(this.paramsQuery),
        ]);

        const processed = this.processChartData(lineData.data);

        // ✅ 手动设置 products 和 productData
        this.salesData.months = processed.months;
        this.salesData.products = processed.equipment; // 接口返回的是产品名
        this.salesData.productData = processed.equipmentData;

        this.salesData.salesPie = pieData.data;

        this.initChart("salesBarChart", this.getSalesBarOption());
        this.initChart("salesPieChart", this.getSalesPieOption());
      } catch (error) {
        console.error("销售数据加载失败:", error);
      }
    },

    getSalesBarOption() {
      const equipmentCount = this.salesData.products.length;
      // const monthCount = this.salesData.months.length; // 不再使用

      // 核心：动态计算柱子宽度，默认按4个设备计算
      const defaultDisplayCount = 4;
      let barWidth;
      if (defaultDisplayCount <= 4) {
        barWidth = 30; // 宽松：30px
      } else if (defaultDisplayCount <= 8) {
        barWidth = 20; // 适中：20px
      } else {
        barWidth = 12; // 拥挤：12px
      }
      barWidth = 12; // 与生产数据保持一致（硬编码）

      // 动态计算barCategoryGap
      const barCategoryGap = equipmentCount > 8 ? "60%" : "80%";

      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          // 改为与生产数据相同的无条件formatter
          formatter: function (params) {
            return params
              .map((p) => `${p.marker} ${p.seriesName}: ${p.value}万吨`)
              .join("<br/>");
          },
        },
        legend: {
          data: this.salesData.products,
          top: "5%",
          icon: "circle",
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 12,
          textStyle: { fontSize: 12 },
          type: equipmentCount > 8 ? "scroll" : "plain",
          pageIconSize: 12,
          pageButtonItemGap: 5,
          // 关键：默认只选中前4个设备
          selected: this.salesData.products.reduce((acc, name, index) => {
            acc[name] = index < 4;
            return acc;
          }, {}),
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%", // 从15%改为10%，移除滑块空间
          containLabel: true,
          top: equipmentCount > 8 ? "20%" : "15%",
        },
        // 关键：移除dataZoom，无滚动条
        // dataZoom: [...],

        xAxis: {
          type: "category",
          data: this.salesData.months, // 完整显示12个月
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: "value",
          name: "万吨",
          nameTextStyle: { padding: [0, 0, 0, -40] },
        },
        // 渲染所有系列，由legend控制显示
        series: this.salesData.products.map((name, index) => ({
          name,
          type: "bar",
          data: this.salesData.productData[index], // 12个月完整数据
          barWidth: barWidth,
          barCategoryGap: barCategoryGap,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: this.gradientColors[index % 17].colorStops[0].color,
              },
              {
                offset: 1,
                color: this.gradientColors[index % 17].colorStops[1].color,
              },
            ]),
            borderRadius: [3, 3, 0, 0],
          },
          emphasis: {
            focus: "series",
            blurScope: "coordinateSystem",
          },
        })),
      };
    },


    getSalesPieOption() {
      return {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}万吨",
        },

        legend: {
          data: this.salesData.salesPie.map((item) => item.name),
          orient: "horizontal",
          bottom: "0%",
          icon: "circle", // ← 关键：圆点
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12,
        },
        series: [
          {
            name: "产品分布",
            type: "pie",

            data: this.salesData.salesPie,
            label: {
              formatter: "{b}\n{c}万吨",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.3)",
              },
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
              color: (params) => {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[0]
                        .color,
                  },
                  {
                    offset: 1,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[1]
                        .color,
                  },
                ]);
              },
            },
            // animationType: 'scale',
            // animationEasing: 'elasticOut',
            // animationDelay: function (idx) {
            //   return Math.random() * 200;
            // },
            radius: "50%",
            // center: ['50%', '50%'],
            // roseType: 'radius',
          },
        ],
      };
    },

    // 设备运行数据图表
    async initEquipmentCharts() {
      try {
        const [lineData, pieData] = await Promise.all([
          equipmentline(this.paramsQuery),
          equipmentpie(this.paramsQuery),
        ]);

        const processed = this.processChartData(lineData.data);
        this.equipmentData = {
          ...this.equipmentData,
          ...processed,
          equipmentPie: pieData.data,
        };

        this.initChart("equipmentBarChart", this.getEquipmentBarOption());
        this.initChart("equipmentPieChart", this.getEquipmentPieOption());
      } catch (error) {
        console.error("设备数据加载失败:", error);
      }
    },

    getEquipmentBarOption() {
      const equipmentCount = this.equipmentData.equipment.length;
      // const monthCount = this.equipmentData.months.length; // 不再使用

      // 核心：动态计算柱子宽度，默认按4个设备计算
      const defaultDisplayCount = 4;
      let barWidth;
      if (defaultDisplayCount <= 4) {
        barWidth = 30; // 宽松：30px
      } else if (defaultDisplayCount <= 8) {
        barWidth = 20; // 适中：20px
      } else {
        barWidth = 12; // 拥挤：12px
      }
      barWidth = 12; // 与生产数据保持一致（硬编码）

      // 动态计算barCategoryGap
      const barCategoryGap = equipmentCount > 8 ? "60%" : "80%";

      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "shadow" },
          // 改为与生产数据相同的无条件formatter
          formatter: function (params) {
            return params
              .map((p) => `${p.marker} ${p.seriesName}: ${p.value}天`) // 注意单位：这里是"天"
              .join("<br/>");
          },
        },
        legend: {
          data: this.equipmentData.equipment,
          top: "5%",
          icon: "circle",
          itemWidth: 10,
          itemHeight: 10,
          itemGap: 12,
          textStyle: { fontSize: 12 },
          type: equipmentCount > 8 ? "scroll" : "plain",
          pageIconSize: 12,
          pageButtonItemGap: 5,
          // 关键：默认只选中前4个设备
          selected: this.equipmentData.equipment.reduce((acc, name, index) => {
            acc[name] = index < 4;
            return acc;
          }, {}),
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "10%", // 从15%改为10%，移除滑块空间
          containLabel: true,
          top: equipmentCount > 8 ? "20%" : "15%",
        },
        // 关键：移除dataZoom，无滚动条
        // dataZoom: [...],

        xAxis: {
          type: "category",
          data: this.equipmentData.months, // 完整显示12个月
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: "value",
          name: "运行天数", // 保持原始单位
          nameTextStyle: { padding: [0, 0, 0, -40] },
        },
        // 渲染所有系列，由legend控制显示
        series: this.equipmentData.equipment.map((name, index) => ({
          name,
          type: "bar",
          data: this.equipmentData.equipmentData[index], // 12个月完整数据
          barWidth: barWidth,
          barCategoryGap: barCategoryGap,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {
                offset: 0,
                color: this.gradientColors[index % 17].colorStops[0].color,
              },
              {
                offset: 1,
                color: this.gradientColors[index % 17].colorStops[1].color,
              },
            ]),
            borderRadius: [3, 3, 0, 0],
          },
          emphasis: {
            focus: "series",
            blurScope: "coordinateSystem",
          },
        })),
      };
    },

    getEquipmentPieOption() {
      // console.log(this.equipmentData.equipmentPie)
      return {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}天",
        },
        legend: {
          data: this.equipmentData.equipmentPie.map((item) => item.name),
          orient: "horizontal",
          bottom: "0%",
          icon: "circle", // ← 关键：圆点
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12, // 图例间隔（可选）
        },
        series: [
          {
            name: "设备运行分布",
            type: "pie",
            animationType: "scale",
            animationEasing: "elasticOut",
            animationDelay: function (idx) {
              return Math.random() * 200;
            },
            radius: "55%",
            center: ["50%", "50%"],
            roseType: "radius",
            data: this.equipmentData.equipmentPie,
            label: {
              formatter: "{b}\n{c}小时",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.3)",
              },
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
              color: (params) => {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[0]
                        .color,
                  },
                  {
                    offset: 1,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[1]
                        .color,
                  },
                ]);
              },
            },
          },
        ],
      };
    },

    // 用电数据图表
    async initElectricityCharts() {
      try {
        const [lineData, pieData] = await Promise.all([
          electricline(this.paramsQuery),
          electricpie(this.paramsQuery),
        ]);

        this.electricityData.months = lineData.data.map((item) => item.month);
        this.electricityData.lineData = lineData.data.map((item) => item.value);
        this.electricityData.pieData = pieData.data;

        this.initChart("electricityLineChart", this.getElectricityLineOption());
        this.initChart("electricityPieChart", this.getElectricityPieOption());
      } catch (error) {
        console.error("用电数据加载失败:", error);
      }
    },

    getElectricityLineOption() {
      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "line" },
        },
        legend: {
          data: ["用电量"],
          icon: "circle",
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12,
        },
        grid: {
          left: "5%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
          top: "15%",
        },
        xAxis: {
          type: "category",
          data: this.electricityData.months,
          axisTick: { alignWithLabel: true },
        },
        yAxis: {
          type: "value",
          name: "单位 MWH",
          nameTextStyle: { padding: [0, 0, 0, -40] },
        },
        series: [
          {
            name: "用电量",
            type: "line",
            data: this.electricityData.lineData,
            symbol: "none",
            symbolSize: 8,
            lineStyle: { width: 3 },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[0].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[0].colorStops[1].color,
                },
              ]),
            },
          },
        ],
      };
    },

    getElectricityPieOption() {
      return {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}MWH",
        },
        legend: {
          data: this.electricityData.pieData.map((item) => item.name),
          orient: "horizontal",
          bottom: "0%",
          icon: "circle", // ← 关键：圆点
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12, // 图例间隔（可选）
        },
        series: [
          {
            name: "用电分布",
            type: "pie",
            // animationType: 'scale',
            // animationEasing: 'elasticOut',
            // animationDelay: function (idx) {
            //   return Math.random() * 200;
            // },
            radius: "50%",
            // center: ['50%', '50%'],
            // roseType: 'radius',
            data: this.electricityData.pieData,
            label: {
              formatter: "{b}\n{c}MWH",
              alignTo: "none",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.3)",
              },
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
              color: (params) => {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[0]
                        .color,
                  },
                  {
                    offset: 1,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[1]
                        .color,
                  },
                ]);
              },
            },
          },
        ],
      };
    },

    // 安全环保数据图表
    async initSafetyCharts() {
      try {
        const [
          inspectionData,
          regionData,
          levelData,
          hazardData,
          typeData,
          violationsData,
        ] = await Promise.all([
          inspectionline(this.paramsQuery),
          workshoppie(this.paramsQuery),
          levelpie(this.paramsQuery),
          hazardline(this.paramsQuery),
          hazardtypepie(this.paramsQuery),
          violationpie(this.paramsQuery),
        ]);

        // 处理巡检数据
        this.safetyData.inspection.months = inspectionData.data.map(
          (item) => item.month
        );
        this.safetyData.inspection.plan = inspectionData.data.map(
          (item) => item.planned
        );
        this.safetyData.inspection.actual = inspectionData.data.map(
          (item) => item.actual
        );

        // 处理隐患数据
        this.safetyData.hazard.months = hazardData.data.map(
          (item) => item.month
        );
        this.safetyData.hazard.found = hazardData.data.map(
          (item) => item.discovered
        );
        this.safetyData.hazard.fixed = hazardData.data.map(
          (item) => item.rectified
        );

        // 处理饼图数据
        this.safetyData.pieData.region = regionData.data;
        this.safetyData.pieData.level = levelData.data;
        this.safetyData.pieData.type = typeData.data;
        this.safetyData.threeViolations = violationsData.data;

        // 初始化图表
        this.initChart("inspectionLineChart", this.getInspectionLineOption());
        this.initChart("hazardBarChart", this.getHazardBarOption());

        // 初始化四个饼图
        [
          "regionPieChart",
          "levelPieChart",
          "typePieChart",
          "threeViolationsPieChart",
        ].forEach((ref) => {
          const title = this.getPieChartTitle(ref);
          this.initChart(ref, this.getPieOption(this.getPieData(ref), title));
        });
      } catch (error) {
        console.error("安全数据加载失败:", error);
      }
    },

    getInspectionLineOption() {
      return {
        tooltip: { trigger: "axis" },
        legend: {
          data: ["计划巡检次数", "实际巡检次数"],
          top: "5%",
          icon: "circle",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12,
          containLabel: true,
          top: "15%",
        },
        xAxis: {
          type: "category",
          data: this.safetyData.inspection.months,
        },
        yAxis: { type: "value", name: "次数" },
        series: [
          {
            name: "计划巡检次数",
            type: "line",
            data: this.safetyData.inspection.plan,
            symbol: "none",
            lineStyle: { width: 3 },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[1].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[1].colorStops[1].color,
                },
              ]),
            },
          },
          {
            name: "实际巡检次数",
            type: "line",
            data: this.safetyData.inspection.actual,
            symbol: "none",
            lineStyle: { width: 3 },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[2].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[2].colorStops[1].color,
                },
              ]),
            },
          },
        ],
      };
    },

    getHazardBarOption() {
      return {
        tooltip: { trigger: "axis", axisPointer: { type: "shadow" } },
        legend: {
          data: ["隐患发现数", "隐患整改数"],
          top: "5%",
          icon: "circle",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12,
          containLabel: true,
          top: "15%",
        },
        xAxis: {
          type: "category",
          data: this.safetyData.hazard.months,
        },
        yAxis: { type: "value", name: "数量" },
        series: [
          {
            name: "隐患发现数",
            type: "bar",
            data: this.safetyData.hazard.found,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[3].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[3].colorStops[1].color,
                },
              ]),
            },
            barWidth: "40%",
          },
          {
            name: "隐患整改数",
            type: "bar",
            data: this.safetyData.hazard.fixed,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[4].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[4].colorStops[1].color,
                },
              ]),
            },
            barWidth: "40%",
          },
        ],
      };
    },

    // 辅助方法
    getPieData(ref) {
      const map = {
        regionPieChart: this.safetyData.pieData.region,
        levelPieChart: this.safetyData.pieData.level,
        typePieChart: this.safetyData.pieData.type,
        threeViolationsPieChart: this.safetyData.threeViolations,
      };
      return map[ref] || [];
    },

    getPieChartTitle(ref) {
      const map = {
        regionPieChart: "隐患区域分布",
        levelPieChart: "隐患级别分布",
        typePieChart: "隐患类型分布",
        threeViolationsPieChart: "三违类型分布",
      };
      return map[ref] || "";
    },

    getPieOption(data, title) {
      return {
        tooltip: {
          trigger: "item",
          formatter: "{b}: {c}个",
        },
        title: {
          text: title,
          left: "center",
          top: "0%",
          textStyle: { fontSize: 14, fontWeight: "bold" },
        },

        legend: {
          orient: "horizontal",
          bottom: "0%",
          icon: "circle", // ← 关键：圆点
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12, // 图例间隔（可选）
        },
        series: [
          {
            type: "pie",
            // animationType: 'scale',
            // animationEasing: 'elasticOut',
            // animationDelay: function (idx) {
            //   return Math.random() * 200;
            // },
            radius: "50%",
            // center: ['50%', '50%'],
            // roseType: 'radius',
            data: data,
            label: {
              formatter: "{b}\n{c}个",
              alignTo: "none",
            },
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.3)",
              },
            },
            itemStyle: {
              borderWidth: 2,
              borderColor: "#fff",
              color: (params) => {
                return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[0]
                        .color,
                  },
                  {
                    offset: 1,
                    color:
                      this.gradientColors[params.dataIndex % 5].colorStops[1]
                        .color,
                  },
                ]);
              },
            },
          },
        ],
      };
    },

    // 备品备件数据图表
    async initSparePartsCharts() {
      try {
        const [quantityData, usageData] = await Promise.all([
          spareline(this.paramsQuery),
          usageline(this.paramsQuery),
        ]);

        // 处理备件数量数据
        const quantity = this.buildQuantity(quantityData.data);
        this.sparePartsData.quantity = quantity;

        // 处理领用数据
        this.sparePartsData.usage.months = usageData.data.map(
          (item) => item.month
        );
        this.sparePartsData.usage.totalQuantity = usageData.data.map(
          (item) => item.totalQuantity
        );
        this.sparePartsData.usage.totalAmount = usageData.data.map(
          (item) => item.totalAmount
        );

        // 初始化图表
        this.initChart("sparePartsComboChart", this.getSparePartsComboOption());
        this.initChart("usageComboChart", this.getUsageComboOption());
      } catch (error) {
        console.error("备件数据加载失败:", error);
      }
    },

    buildQuantity(list) {
      // 固定月份表
      const months = [
        "1月",
        "2月",
        "3月",
        "4月",
        "5月",
        "6月",
        "7月",
        "8月",
        "9月",
        "10月",
        "11月",
        "12月",
      ];

      // 收集所有备件名
      const nameMap = new Map();
      list.forEach(({ spareData }) => {
        Object.keys(spareData).forEach((k) => nameMap.set(k, 1));
      });
      const names = Array.from(nameMap.keys());

      // 建立月份索引
      const monthIdx = Object.fromEntries(
        list.map(({ month }, i) => [month.padStart(2, "0"), i])
      );

      // 构建数据矩阵
      const dataMatrix = names.map(() => new Array(12).fill(null));
      list.forEach(({ month, spareData }) => {
        const mIdx = monthIdx[month];
        names.forEach((n, nIdx) => {
          if (n in spareData) dataMatrix[nIdx][mIdx] = spareData[n];
        });
      });

      return {
        months,
        spareParts: names.map((name, i) => ({
          name,
          data: dataMatrix[i],
        })),
      };
    },

    getSparePartsComboOption() {
      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross" },
        },
        legend: {
          data: this.sparePartsData.quantity.spareParts.map(
            (item) => item.name
          ),
          top: "5%",
          icon: "circle",
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
          top: "15%",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.sparePartsData.quantity.months,
        },
        yAxis: {
          type: "value",
          name: "数量(个)",
        },
        series: this.sparePartsData.quantity.spareParts.map((item, index) => {
          if (item.name === "托辊") {
            return {
              name: item.name,
              type: "bar",
              data: item.data,
              barWidth: "20%",
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: this.gradientColors[0].colorStops[0].color,
                  },
                  {
                    offset: 1,
                    color: this.gradientColors[0].colorStops[1].color,
                  },
                ]),
              },
            };
          } else {
            return {
              name: item.name,
              type: "line",
              data: item.data,
              symbol: "none",
              symbolSize: 8,
              lineStyle: { width: 2 },
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  {
                    offset: 0,
                    color: this.gradientColors[index % 5].colorStops[0].color,
                  },
                  {
                    offset: 1,
                    color: this.gradientColors[index % 5].colorStops[1].color,
                  },
                ]),
              },
            };
          }
        }),
      };
    },

    getUsageComboOption() {
      return {
        tooltip: {
          trigger: "axis",
          axisPointer: { type: "cross" },
        },
        legend: {
          data: ["领用总数量", "领用总金额"],
          top: "5%",
          icon: "circle",
          itemWidth: 10, // 圆点直径
          itemHeight: 10, // 圆点直径
          itemGap: 12,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
          top: "15%",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: this.sparePartsData.usage.months,
        },
        yAxis: [
          {
            type: "value",
            name: "数量(个)",
            position: "left",
          },
          {
            type: "value",
            name: "金额(万元)",
            position: "right",
          },
        ],
        series: [
          {
            name: "领用总数量",
            type: "bar",
            data: this.sparePartsData.usage.totalQuantity,
            yAxisIndex: 0,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[1].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[1].colorStops[1].color,
                },
              ]),
            },
            barWidth: "20%",
          },
          {
            name: "领用总金额",
            type: "line",
            data: this.sparePartsData.usage.totalAmount,
            yAxisIndex: 1,
            symbol: "none",
            symbolSize: 8,
            lineStyle: { width: 2 },
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                {
                  offset: 0,
                  color: this.gradientColors[2].colorStops[0].color,
                },
                {
                  offset: 1,
                  color: this.gradientColors[2].colorStops[1].color,
                },
              ]),
            },
          },
        ],
      };
    },

    // 辅助方法：获取设备颜色
    getEquipmentColor(name) {
      const colors = {
        破碎机: "#5470C6",
        制砂机: "#91CC75",
        筛分机: "#FAC858",
        细碎车间: "#5470C6",
        制砂车间: "#91CC75",
        回笼车间: "#FAC858",
        粗碎车间: "#EE6666",
      };
      return colors[name];
    },

    // 辅助方法：获取产品颜色
    getProductColor(name) {
      const colors = {
        全部产品: "#5470C6",
        "5-10": "#91CC75",
        "10-20": "#FAC858",
        "20-30": "#EE6666",
        机制砂: "#73A0FA",
      };
      return colors[name];
    },
  },
};
</script>

<style scoped lang="scss">
.times {
  width: 120px;
  height: 24px;
  display: flex;
  align-items: center;
}

.times ::v-deep .el-input__inner {
  width: 120px !important;
  height: 24px !important;
  line-height: 24px !important;
  padding-top: 0 !important;
  padding-bottom: 0 !important;
  border-radius: 30px;
  background: rgba(243, 247, 251, 1);
}

/* 3. 图标垂直居中 */
.times ::v-deep .el-input__icon {
  line-height: 24px;
}

.card-container {
  width: 100%;
  overflow: hidden;
  padding: 0;

  .cards-wrapper {
    //display: flex;
    //gap: 16px;
    //margin-left: 0 !important;
    ///* 强制左侧无边距 */
    //overflow-x: auto;
    //margin-right: -16px;
    /* 添加横向滚动支持 */
    margin: 0 -10px;
    display: flex;
    flex-wrap: nowrap;
    gap: calc(20 / 1920 * 100vw);
  }

  .card-item {
    //flex: 0 0 auto;
    //width: calc(20% - 16px);
    flex: 1 0 0%;
    min-width: 0;
    padding: 0 !important;
    /* 动态计算宽度（考虑间距） */
    height: 96px;

    /* 关键：消除首尾额外间距 */
    &:first-child {
      margin-left: 0;
    }

    &:last-child {
      margin-right: 0;
    }
  }
}

.el-card {
  border-radius: 10px !important;
  margin: 0 !important;
}

.card-content {
  text-align: center;
  color: white;
  padding: 8px;
  height: 96px;
  border-radius: 6px;
}

.title {
  margin-top: 10px;
  color: white;
  margin-bottom: 10px;
  font-weight: 600;
  font-size: 1rem;
  white-space: wrap;
  /* 不换行 */
  overflow: hidden;
  /* 溢出隐藏 */
  text-overflow: ellipsis;
}

.value {
  font-family: PingFang SC;
  font-weight: 600;
  font-style: Semibold;
  font-size: 20px;
}

.el-card__body {
  padding: 0 !important;
  margin: 0 !important;
}

.card-item.last-card {
  margin-right: 0 !important;
}

.section {
  margin: 16px;

  .el-row {
    .el-col {
      height: 100%;

      .box-padding-16 {
        margin: 0 !important;
      }

      .box-margin-right-none {
        width: 100%;
      }

      .box-margin-left-none {
        width: calc(100% - 16px) !important;
        margin-right: 8px !important;
      }

      .box-right {
        height: 100%;
        display: flex;
        flex-direction: column;

        .box-padding-16-flex {
          height: 100%;
        }

        .chart-row {
          flex: 1;
        }
      }
    }
  }
}

.titles {
  font-weight: bold;
  font-size: 16px;
  border-left: 5px solid blue;
  padding-left: 10px;
  margin: 10px 0 20px 0;
}

.divider {
  width: 16px;
  /* 间隙宽度 */
  background: #f5f5f5;
  /* 你想要的灰色 */
  border-radius: 4px;
  /* 圆角更精致 */
  flex-shrink: 0;
  /* 防止被压缩 */
}

.chart-row {
  display: flex;
  width: 100%;
  margin-bottom: 20px;
}

.bar-chart {
  //width: 70%;
  width: 100%;
  height: 300px;
  background: #fff;
  margin-right: 16px;
}

.full-bar-chart {
  width: 100%;
  height: 300px;
}

.pie-chart {
  //width: 30%;
  width: 100%;
  height: 300px;
}

.full-line-chart {
  width: 60%;
  height: 300px;
}

/* 添加图表容器最小高度保证显示 */
.full-line-chart,
.full-bar-chart {
  min-height: 300px;
}

/* 新增安全环保数据样式 */
.pie-container {
  width: 50%;
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
}

.pie-item {
  width: 48%;
  height: 250px;
  margin-bottom: 20px;
}

.half-chart {
  //width: 50%;
  width: 100%;
  height: 300px;
}

/* 新增安全环保数据样式优化 */
.chart-row {
  display: flex;
  width: 100%;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.pie-row {
  display: flex;
  //width: 50%;
  width: 100%;
  justify-content: space-around;
}

.pie-chart {
  //width: 45%;
  width: 100%;
  height: 300px;
}

.pie-charts {
  width: 50%;
  height: 300px;
  margin-top: 16px;
}

/* 备品备件数据样式 */
.spare-parts-chart {
  width: 100%;
  height: 400px;
  margin-bottom: 20px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .chart-row {
    flex-direction: column;
  }

  .half-chart,
  .pie-charts {
    width: 100%;
    margin-bottom: 20px;
  }

  .spare-parts-chart {
    height: 350px;
  }
}
</style>
